import {assetUrl} from "../config";
import moment, {Moment} from 'moment';
import {PageInterface} from "../net/instance/CommenModelInstance";
import {Animated, InteractionManager, Linking} from "react-native";
import * as _ from 'lodash'
import toast from "../component/common/ToastProxy";

export function isPhoneAvailable(str: string): boolean {
    const myreg = /^.{11}$/;
    if (!myreg.test(str)) {
        return false;
    } else {
        return true;
    }
}

export function randomNumber(codeLength): number {
    var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);//随机数
    var code = "";
    for (var i = 0; i < codeLength; i++) {//循环操作
        var index = Math.floor(Math.random() * 10);//取得随机数的索引（0~35）
        code += random[index];//根据索引取得随机数加到code上
    }
    return +code;
}

export function getAssetUrl(url: string) {
    return `${assetUrl}${url}`
}

export function keyExtractor(item: any, index: number) {
    return `${index}`
}

export function isSameDate(d1: Date | string, d2: Date | string) {
    return moment(d1).unix() === moment(d2).unix();
}

export function dateFormat(d1: Date | string | Moment, format: string = "YYYY-MM-DD HH:mm:ss") {
    if (d1 == null) return moment().format(format);
    return moment(d1).format(format);
}

export function getTime(date: Date | string) {
    return moment(date).unix();
}

export function transformRotateNumberToDeg(num: Animated.Value) {
    return num.interpolate({inputRange: [0, 360], outputRange: ['0deg', '360deg']})
}

export const defaultObj: any = {};
export const defaultArr: any = [];
export const defaultPage: PageInterface = {
    pageNum: 1,
    pageSize: 6
};

export function PromiseWrapper(callback: (resolve) => void) {
    return new Promise(resolve => {
        callback(resolve);
    })
}

export function getImageSizeRatio(currentWidthOrHeight: number, actuallyWidthOrHeight: number): number {
    return currentWidthOrHeight / actuallyWidthOrHeight;
}

export function toFixed(num: number, suffix: number = 2) {
    return num.toFixed(suffix);
}

/**
 * 移除 null undefined的属性
 * @param obj
 * @returns {any}
 */
export function excludeEmpty(obj) {
    const newObj = Object.create(null);
    for (let key in obj) {
        if (!_.isEmpty(obj[key]) || "null" !== obj[key] || _.isInteger(obj[key])) {

            if (_.isPlainObject(obj[key])) {
                const res = excludeEmpty(obj[key]);
                if (res) {
                    newObj[key] = res
                }
            } else {
                newObj[key] = obj[key]
            }

        }
    }
    return newObj;
}

/**
 * 验证对象是否有属性为空
 */
export function validObjHasEmpty(obj: Object, ...withoutKey: string[]): boolean {
    return _.some(obj, (value, key) => {
        if (_.indexOf(withoutKey, key) !== -1) return false;
        return _.isEmpty(value);
    })
}

export const afterAnimation = InteractionManager.runAfterInteractions;

export function valWithDefault(val) {
    if (_.isEmpty(val)) {
        return defaultObj;
    }
    return val;
}

export function numberWithDefault(val) {
    if (!_.isNumber(val)) {
        return 0;
    }
    return val;
}

type DefaultValueWithPromiseValueTuple<D, T> = [D, Promise<T>];

export function getDefaultValueWithPromiseValue<D, T>(defaultValue: D, promise: Promise<T>): DefaultValueWithPromiseValueTuple<D, T> {
    return [defaultValue, promise];
}

export function callPhone(phone: string) {
    Linking.canOpenURL(`tel:${phone}`).then(supported => {
        if (!supported) {
            toast("不支持拨打电话");
        } else {
            return Linking.openURL(`tel:${phone}`);
        }
    }).catch(err => toast("不支持拨打电话"));
}

export function isEmpty(obj) {
    return _.isEmpty(obj)
}